﻿//using System.Collections;
//using System.Collections.Generic;
//using UnityEngine;

////范形填入，万能类型
//public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
//{
//    private static T instance;
//    public static T Instance
//    {
//        get
//        {
//            if (instance == null)
//            {
//                instance = FindObjectOfType<T>();
//            }
//            return instance;
//        }
//    }
//    // Start is called before the first frame update
//    private void Awake()
//    {
//        if (instance != null)
//        {
//            Destroy(gameObject);
//        }
//    }
//}
using UnityEngine;

public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance;
    private static readonly object lockObj = new object(); // 线程锁对象
    private static bool isShuttingDown = false; // 应用退出标志

    public static T Instance
    {
        get
        {
            if (isShuttingDown)
            {
                Debug.LogWarning($"单例 {typeof(T)} 正在销毁，返回空值");
                return null;
            }

            lock (lockObj) // 线程锁
            {
                if (instance == null)
                {
                    // 1. 尝试查找现有实例
                    instance = FindObjectOfType<T>();

                    // 2. 如果不存在则创建新实例
                    if (instance == null)
                    {
                        var singletonObject = new GameObject($"{typeof(T)} (Singleton)");
                        instance = singletonObject.AddComponent<T>();
                        DontDestroyOnLoad(singletonObject); // 跨场景保护
                    }
                }
                return instance;
            }
        }
    }

    protected virtual void Awake()
    {
        lock (lockObj)
        {
            if (instance == null)
            {
                instance = this as T;
                DontDestroyOnLoad(gameObject); // 维持单例跨场景存在
            }
            else if (instance != this)
            {
                Destroy(gameObject); // 销毁重复实例
            }
        }
    }

    protected virtual void OnApplicationQuit()
    {
        isShuttingDown = true; // 标记应用退出
    }

    protected virtual void OnDestroy()
    {
        if (instance == this)
        {
            instance = null; // 清理引用
        }
    }
}
